from django.db.models.expressions import result
from django.db.models.fields import return_None
from django.shortcuts import render
from django.http import JsonResponse
from django.core.cache import cache
import json
from db_model.models import User #导入user表映射

# Create your views here.
def health_check(request):
    return JsonResponse({'status': 'ok'}, safe=False)

def log_api(request):
    data=json.loads(request.body)
    msg=data['msg']
    print("前端发来了！"+msg)
    return JsonResponse("ok",safe=False)


def redis_api(request):
    res = cache.set('test', 123, timeout=10)
    if res:
        return JsonResponse("ok",safe=False)
    else:
        return JsonResponse("fail",safe=False)

def register(request):   #注册方法
    data = json.loads(request.body)
    try:
        User.objects.create(
            username=data['username'],
            password=data['password'],
            email=data['email'],
        )
    except IntegrityError:
        return JsonResponse("fail",safe=False)
    return JsonResponse("ok",safe=False)

def login(request):   #登陆方法，基于查找
    data = json.loads(request.body)
    res = User.objects.filter(
        email=data['email'],
        password=data['password']
    ).exists()
    if res:
        return JsonResponse("ok",safe=False) #登录成功返回ok
    else:
        return JsonResponse("fail",safe=False) #登录失败，返回fail